import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'


Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  { path: '/', redirect: '/login' },
  { path: '/home', component: Home }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  //如果用户访问的是login页面 正常放行
  if (to.path === '/login') return next()
  //将保存在客户端的token取出来，
  const tokenStr = window.sessionStorage.getItem('token')
  //如果token不存在 则证明用户没有登录 强制重定向到 login 页面
  if (!tokenStr) return next('/login')
  //否则 正常放行
  next()

})


export default router
